package com.strato.mvc.view.velocity.v1_0_0;

import java.util.Locale;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.strato.mvc.api.v1_0_0.view.View;
import com.strato.mvc.api.v1_0_0.view.ViewName;
import com.strato.mvc.api.v1_0_0.view.ViewResolver;
import com.strato.mvc.view.velocity.v1_0_0.resource.BundleResourceLoader;

public class VelocityViewResolver implements ViewResolver,VelocityEngineFactory {

	private VelocityEngine velocityEngine;
	
	public static String NAME="vm";
	
	public void initVelocityEngine(){
		Properties p=new Properties();
		p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		p.setProperty(Velocity.SET_NULL_ALLOWED, "true");
		p.setProperty(Velocity.RESOURCE_LOADER, "bundle");
		p.setProperty(Velocity.VM_LIBRARY, "vm:/macro/macro@strato.mvc.view.velocity.v1_0_0");
		p.setProperty("bundle.resource.loader.class", BundleResourceLoader.class.getName());
		velocityEngine=new VelocityEngine();
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		try{
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
			velocityEngine.init(p);
		}finally{
			Thread.currentThread().setContextClassLoader(cl);
		}
	}
	
	@Override
	public int getOrder() {
		return 2;
	}

	@Override
	public View resolveView(ViewName viewName,Locale locale) {
		if(locale!=null){
			ViewName vnl=ViewName.parse(viewName.toString());
			vnl.setPath(vnl.getPath()+"_"+locale.toLanguageTag());
			View view = resolveView(vnl,null);
			if(view!=null){
				return view;
			}
		}
		Template template=null;
		try{
			template = velocityEngine.getTemplate(viewName.toString());
		}catch(ResourceNotFoundException e){
			
		}
		if(template==null){
			return null;
		}
		VelocityView view=new VelocityView();
		view.setTemplate(template);
		return view;
	}

	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

}
